from binascii import hexlify, unhexlify
from configparser import ConfigParser
from utils import randkey
import struct
from qqtea import encrypt, decrypt
from ipaddress import ip_address

cf_parser = ConfigParser()
cf_parser.read("./config.ini")

HEADER = "02" + cf_parser.get("basic", "Version")


class Package:
    def __init__(self, protocal, data):
        self.protocal = protocal()
        self.data = data
        qq = self.data.get("qq")
        self.HEADER = HEADER + self.protocal.num + randkey(4) + hexlify(struct.pack(">I", qq)).decode() 

    def serialize(self):
        packed = self.hexlify()
        return unhexlify(packed)

    def hexlify(self):
        return self.HEADER + self.protocal.hexlify(self.data) + "03"

    def analyze(self, resp):
        return self.protocal.analyze(resp)

    def __str__(self):
        pass

class Protocal:
    def __init__(self, num):
        self.num = num
    def hexlify(self):
        pass
        
class Protocal0825(Protocal):
    def __init__(self):
        super().__init__("0825")
        self.count = 0
        self.qqtea_key = randkey(32)
        self.hdc_key = randkey(50)
        print(self.hdc_key)
    def hexlify(self, data):
        qq = data.get("qq")
        server = data.get("server_ip")
        self.encrypt(qq, server)
        print(len(self.cyphertext))
        ret = "0300" + \
            hexlify(struct.pack(">b", self.count)).decode() + \
            "000101010000" + \
            "6955" + \
            "00000000" + \
            self.qqtea_key + \
            hexlify(encrypt(unhexlify(self.cyphertext), unhexlify(self.qqtea_key))).decode()
        self.count += 1
        return ret 
    def encrypt(self, qq, server_ip):
        self.cyphertext = "0018001600010000" + \
            "0457" + \
            "000000010000" + \
            "1633" + \
            hexlify(struct.pack(">I", qq)).decode() + \
            "00000000030900080001" + \
            hexlify(ip_address(server_ip).packed).decode() + \
            "000400360012000200010000000000000000000000000000" + \
            "0114001d0103" + \
            "0019" + \
            self.hdc_key
    def analyze(self, resp):
        cyphertext = resp[14:-1]
        message = hexlify(decrypt(cyphertext, unhexlify(self.qqtea_key)))
        return message


if __name__ == '__main__':        
    _0825 = Protocal0825
    data = {"qq": 414446770, "server_ip": "0.0.0.0"}
    a = Package(_0825, data)
    print(a.hexlify())
    print(a.hexlify())
    print(len(a.serialize()))

    
